package cc.ufinity.networkdiagnose.manager;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.example.authforcmcc.Global;

import android.app.Activity;
import cc.ufinity.networkdiagnose.app.AppLogs;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.util.HttpUtils;

/**
 * Web登录及下线认证测试类
 * 
 * @author svenke
 * 
 */
public final class WebAuthManager extends AbstractManager {

    private Activity ctx;
    public  HttpClient client;
    private String strAuthLog = "";//认证日志
    private String strLogoutLog = "";//下线日志
    
    public WebAuthManager(Activity context) {
			client = HttpUtils.getSSLHttpClient();
    }
    
    private String userName;
	private String passWord;
	
	private String urlSecond;
	private Map<String, String> logoutParas;
	private String logoutUrl;
	
	private long startTime;
	private long endTime;
 

	public long getStartTime() {
		return startTime;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}

	public long getEndTime() {
		return endTime;
	}

	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}

	public boolean logout2() {
		boolean success = false;
		int i = 0;
		do{
			i++;
			success = logout1();
			if (success) {
				break;
			}
			try {
				Thread.sleep(500);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}while(!success && i<4);
		return success;
	}
	
	public boolean logout1(){
//		if(isOFFLine()){
//			System.out.println("已下线");
//			return true;
//			}
		boolean sucess = false;
		strLogoutLog = "";
		logoutParas = GlobalApp.logoutParas == null?Global.logoutParascmcc:GlobalApp.logoutParas;
		logoutUrl = GlobalApp.logoutUrl == null?Global.logoutUrlcmcc:GlobalApp.logoutUrl;
		try {
			HttpPost post = new HttpPost(logoutUrl);
			post.setEntity(new UrlEncodedFormEntity(setlogoutRequestParams(logoutParas)));
			HttpResponse response = client.execute(post);
			int sc = response.getStatusLine().getStatusCode();
			String result = EntityUtils.toString(response.getEntity());
		//	System.out.println("下线页："+result);
			if (sc == HttpStatus.SC_OK) {
				if (result.contains("下线成功")) {
					sucess = true;
					GlobalApp.logoutParas = new HashMap<String, String>();
					GlobalApp.loginurl = new String();
					System.out.println("下线成功！！！！！！！！！！！！！！");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return sucess;
	}
	
	//增加失败重试
	public boolean auth( String url, String userName, String strPassWord) {
		 
		System.out.println("web  认证开始-----------------------");
		boolean success = false;
		int i = 0;
		do{
			i++;
			success = auth1(url, userName, strPassWord);
			if (success) {
				break;
			}
			try {
				Thread.sleep(500);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}while(!success && i<4);
		if (!success) {// 认证失败将失败信息写入日志
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyyMMddHHmmssSSS");
			Date curDate = new Date(System.currentTimeMillis());
			AppLogs.logData += "web认证---------时间："+formatter.format(curDate)+"\n"+strAuthLog;
			System.out.println("strAuthLog--------" + strAuthLog);
		}
		return success;
	}
	
	public boolean auth1(String url,String userName, String strPassWord) {
		strAuthLog = "";
		this.userName = userName;
		this.passWord = strPassWord;
		boolean success = false;
		strAuthLog += "web认证开始" + "\n"; 
		//String url = "http://www.baidu.com";
		HttpGet get = new HttpGet(url+"?random="+Math.random());
		try {
			// step1:index.php
			HttpResponse response = client.execute(get);
			int sc = response.getStatusLine().getStatusCode();
			String result = EntityUtils.toString(response.getEntity());
			if (result.contains("百度一下") || result.contains("baidu")) {
				System.out.println("已经在线！！！！！！！！！！！！！！");
				return true;
			}
			System.out.println("redirect返回结果：" + result);
//			strAuthLog += "redirect返回结果：" + result + "\n"; 
			if ((sc == HttpStatus.SC_MOVED_TEMPORARILY)
					|| sc == HttpStatus.SC_OK
					|| (sc == HttpStatus.SC_MOVED_PERMANENTLY)
					|| (sc == HttpStatus.SC_SEE_OTHER)
					|| (sc == HttpStatus.SC_TEMPORARY_REDIRECT)) {
				//解析各参数值
				urlSecond = getInputUrl(result,"frame", "src");
	                //step2:'https://221.176.1.140:8090/wlan/input.do?wlanacip=120.209.173.9&wlanacname=0010.0551.551.00&wlanuserip=10.245.230.243&wlanacssid=CMCC&uaId=PCUA0006
	        		get = new HttpGet(urlSecond);
	        		response = client.execute(get);
	        		result = EntityUtils.toString(response.getEntity());
	        		System.out.println("认证页面："+result);
//	        		strAuthLog += "认证页面："+result + "\n";
	        		Map<String, String> mapParas = parseParamst(result,"input");//获a取hidden的参数
	        		//https://221.176.1.140:8090/wlan/login.do
	        		String dologinUrl = logingdo(result, "form", "action");
	        		HttpPost post = new HttpPost(dologinUrl);
	        		post.setEntity(new UrlEncodedFormEntity(setRequestParams(mapParas)));//设置请求参数
	        		response = client.execute(post);
	        		result = EntityUtils.toString(response.getEntity());
	        		System.out.println("登录返回结果："+result);
//	        		strAuthLog += "登录返回结果："+result + "\n";
	        		if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
	        			if(result.contains("loginrr.jpg") || result.contains("尊敬的用户") || result.contains("您当前使用的套餐")){
	        				System.out.println("登录成功！！！！！！！！！！！！！！");
	        				logoutParas = parseParamst(result,"input");//获取下线参数
	        				logoutUrl = logoutdo(result,"form","action","portal");
	        				GlobalApp.logoutParas = logoutParas;
	        				GlobalApp.logoutUrl = logoutUrl;
	        				success = true;
	        			}
	        		//	logout();
	        		}
				
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw, true));
			String str = sw.toString();
			strAuthLog += "web认证中的异常信息:+" + e.toString() + "\n"+str +"\n";
		}
		return success;
		// return wh.CMCCLogin(userName, pwd);
	}

	public boolean canGotoWeb() {
		HttpGet get = new HttpGet("http://www.baidu.com");
		HttpResponse response;
		try {
			response = client.execute(get);
			int sc = response.getStatusLine().getStatusCode();
			String content = EntityUtils.toString(response.getEntity());
			System.out.println(content);
			if (sc == HttpStatus.SC_OK) {
				if (content.contains("百度一下，你就知道 ")) {
					return true;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	 private String getInputUrl(String content, String tag, String attr) {
	        String inputUrl = null;
	        Document doc = Jsoup.parse(content);
	        Element e = doc.select(tag).first();
	        if (e != null) {
	            String src = e.attr(attr);
	            inputUrl = src;
	          //  httpParams = StringUtils.parseURL(src);
	        } 
	        return inputUrl;
	    }
	 
	private String logingdo(String content, String tag, String attr) {
		String loginUrl = null;
		Document doc = Jsoup.parse(content);
		Element e = doc.select(tag).first();
		if (e!=null) {
			loginUrl = e.attr(attr);
		}
		return loginUrl;
	}
	
	private String logoutdo(String content, String tag, String attr, String name) {
		String logoutUrl = null;
		Document doc = Jsoup.parse(content);
		for(int i=0 ; i<doc.select(tag).size() ; i++){
			Element e = doc.select(tag).get(i);
			if(name.equals(e.attr("name"))){
				logoutUrl = e.attr(attr);
				break;
			}
		}
		return logoutUrl;
	}
	
	 private List<NameValuePair> setlogoutRequestParams(Map<String, String>mapParams) {
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("button2", "下  线"));
	        params.add(new BasicNameValuePair("username", mapParams.get("username")));
	        params.add(new BasicNameValuePair("backupInfo", mapParams.get("backupInfo")));
	        params.add(new BasicNameValuePair("logintime", mapParams.get("logintime")));
	        params.add(new BasicNameValuePair("remaintime", mapParams.get("remaintime")));
	        params.add(new BasicNameValuePair("areacode", mapParams.get("areacode")));
	        params.add(new BasicNameValuePair("wlanacip", mapParams.get("wlanacip")));
	        params.add(new BasicNameValuePair("wlanacname", mapParams.get("wlanacname")));
	        params.add(new BasicNameValuePair("wlanuserip", mapParams.get("wlanuserip")));
	        params.add(new BasicNameValuePair("productid", mapParams.get("productid")));
	        
	        params.add(new BasicNameValuePair("effecttime", mapParams.get("effecttime")));
	        params.add(new BasicNameValuePair("expiretime", mapParams.get("expiretime")));
	        params.add(new BasicNameValuePair("keystr", mapParams.get("keystr")));
	        params.add(new BasicNameValuePair("cf", mapParams.get("cf")));
	        params.add(new BasicNameValuePair("logouttype", mapParams.get("logouttype")));
	        params.add(new BasicNameValuePair("logonsessid", mapParams.get("logonsessid")));
	        params.add(new BasicNameValuePair("portion", mapParams.get("portion")));
	        params.add(new BasicNameValuePair("wlanacssid", mapParams.get("wlanacssid")));
	        params.add(new BasicNameValuePair("uaId", mapParams.get("uaId")));
	        params.add(new BasicNameValuePair("Token", mapParams.get("Token")));
	        params.add(new BasicNameValuePair("passflag", mapParams.get("passflag")));
	        params.add(new BasicNameValuePair("passtype", mapParams.get("passtype")));
	        return params;
	    }
 
	 private List<NameValuePair> setRequestParams(Map<String, String>mapParams) {
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("staticusername", userName));
	        params.add(new BasicNameValuePair("staticpassword", passWord));
	        params.add(new BasicNameValuePair("loginmode", mapParams.get("loginmode")));
	        params.add(new BasicNameValuePair("wlanacip", mapParams.get("wlanacip")));
	        params.add(new BasicNameValuePair("wlanacname", mapParams.get("wlanacname")));
	        params.add(new BasicNameValuePair("wlanuserip", mapParams.get("wlanuserip")));
	        params.add(new BasicNameValuePair("wlanacssid", mapParams.get("wlanacssid")));
	        params.add(new BasicNameValuePair("portion", mapParams.get("portion")));
	        params.add(new BasicNameValuePair("obsReturnAccount", mapParams.get("obsReturnAccount")));
	        params.add(new BasicNameValuePair("uaId", mapParams.get("uaId")));
	        params.add(new BasicNameValuePair("Token", mapParams.get("Token")));
	        
	        params.add(new BasicNameValuePair("button2", "登 录"));
	        params.add(new BasicNameValuePair("sloginvalidate", "输入验证码"));
	        params.add(new BasicNameValuePair("sloginhiddenvalidate", ""));
	        params.add(new BasicNameValuePair("spid", ""));
	        return params;
	    }

	private Map<String, String> parseParamst(String content,
			String tag) {
		Map<String, String> httpParams = new HashMap<String, String>();
		Document doc = Jsoup.parse(content);
		try {
			for (int i = 0; i < doc.select(tag).size(); i++) {
				Element e = doc.select(tag).get(i);
				// System.err.println("e:"+e.toString());
				// TODO: handle exception
				String type = e.attr("type");
				if ("hidden".equals(type)) {
					String name = e.attr("name");
					String value = e.attr("value");
					System.err.println("id:" + name + "  value:" + value);
					httpParams.put(name, value);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return httpParams;
	}
	
	// if offline return true;
	public boolean isOFFLine(){
		boolean status = canGotoWeb();
		return !status;
	}
    
}
